package com.ld.manageBook.service.impl;

import com.ld.manageBook.DAO.BookDAO;
import com.ld.manageBook.bean.Books;
import com.ld.manageBook.bean.User;
import com.ld.manageBook.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
	private BookDAO bookDAO = new BookDAO();
	@Override
	public List<Books> getAllBooks() {
		List<Books> books = bookDAO.queryMulti("select * from books",Books.class);
		return books;
	}

	@Override
	public int deleteBookById(Integer id) {
		return bookDAO.update("delete from books where id = ?",id);
	}

	@Override
	public Books getBookById(Integer id) {
		return bookDAO.querySingle("select * from books where id = ?",Books.class,id);
	}

	@Override
	public int changeBookById(Books book) {
		return bookDAO.update("update books set name = ?,author = ?,price = ? ,remarks = ?,number = ? where id = ?",book.getName(),book.getAuthor(),book.getPrice(),book.getRemarks(),book.getNumber(),book.getId());
	}

	@Override
	public int addBook(Books book) {
		return bookDAO.update("insert into books(name,author,price,remarks,number) values(?,?,?,?,?)",book.getName(),book.getAuthor(),book.getPrice(),book.getRemarks(),book.getNumber());
	}

	@Override
	public Books getBookByName(String name) {
		return bookDAO.querySingle("select * from books where name = ?",Books.class,name);
	}

	@Override
	public int updateBookNumber(Integer id, Integer number) {
		Books bookById = getBookById(id);
		if(bookById != null){
			return bookDAO.update("update books set number = ? where id = ?",bookById.getNumber() - number,id);
		}else return 0;
	}

	@Override
	public int getBookNumberByName(String name) {
		return (int)bookDAO.queryScalar("select number from books where name = ?",name);
	}

	@Override
	public int returnBook(String name, Integer returnNumber) {
		int i = getBookNumberByName(name);
		return bookDAO.update("update books set number = ? where name = ?",i + returnNumber,name);
	}
}
